package hms.FrontDeskModule;


import java.awt.event.ActionEvent;

import hms.generic.AbstractGlobalView;
import hms.master.*;
import hms.permissions.Permission;
import hms.database.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JPanel;

import java.awt.GridBagLayout;

import javax.swing.JTable;
import javax.swing.JOptionPane;
import javax.swing.JList;
import java.awt.GridBagConstraints;
import javax.swing.table.DefaultTableModel;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import javax.swing.border.TitledBorder;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextArea;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import java.awt.Color;


public class GuestServicesView extends AbstractGlobalView  {
	
	private JPanel contentPane;
	private JTextField display;
	private JPanel panel;
	private JPanel panel_2;
	private JPanel panel_3;
	private JPanel panel_4;
	private JScrollPane scrollPane;
	private JScrollPane scrollPane_2;
	private JScrollPane scrollPane_3;
	private JButton guestSearchButton;
	private JButton orderButton;
	private JList guestList;
	private JTextArea infoTextArea;
	private Vector<String> guestNameVector = new Vector<String>();
	private Vector<String> guestServiceVector=new Vector<String>();
	private JList serviceList;
	private int guestID;
	private JButton addServiceButton;

	/**
	 * Create the frame.
	 */
	public GuestServicesView() {
		initComponent();
		super.update(contentPane);
		super.display();
	}
	
	private void initComponent(){
		 contentPane = new JPanel();
		 contentPane.setBorder(new TitledBorder(null, "Guest Service", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		 
		 panel = new JPanel();
		 panel.setBorder(new TitledBorder(null, "Guest", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		 
		 panel_2 = new JPanel();
		 panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Guest Information", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		 
		 panel_3 = new JPanel();
		 panel_3.setBorder(new TitledBorder(null, "Available Service", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		 
		 panel_4 = new JPanel();
		 
		 display = new JTextField();
		 display.setEditable(false);
		 display.setColumns(10);
		 
		 JLabel lblYourSelection = new JLabel("Your Selection:");
		 GroupLayout gl_contentPane = new GroupLayout(contentPane);
		 gl_contentPane.setHorizontalGroup(
		 	gl_contentPane.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_contentPane.createSequentialGroup()
		 			.addContainerGap()
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addComponent(panel, GroupLayout.PREFERRED_SIZE, 201, GroupLayout.PREFERRED_SIZE)
		 					.addGap(33)
		 					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 						.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
		 						.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)))
		 				.addComponent(panel_4, 0, 0, Short.MAX_VALUE)
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addComponent(lblYourSelection, GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
		 					.addPreferredGap(ComponentPlacement.RELATED)
		 					.addComponent(display, GroupLayout.PREFERRED_SIZE, 156, GroupLayout.PREFERRED_SIZE)
		 					.addGap(371)))
		 			.addGap(0))
		 );
		 gl_contentPane.setVerticalGroup(
		 	gl_contentPane.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_contentPane.createSequentialGroup()
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addGap(14)
		 					.addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)
		 					.addGap(18)
		 					.addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))
		 				.addGroup(gl_contentPane.createSequentialGroup()
		 					.addContainerGap()
		 					.addComponent(panel, GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)))
		 			.addPreferredGap(ComponentPlacement.RELATED)
		 			.addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 49, GroupLayout.PREFERRED_SIZE)
		 			.addGap(23)
		 			.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
		 				.addComponent(lblYourSelection, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
		 				.addComponent(display, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
		 );
		 panel_3.setLayout(new BoxLayout(panel_3, BoxLayout.X_AXIS));
		 
		 scrollPane_3 = new JScrollPane();
		 panel_3.add(scrollPane_3);
		 
		 serviceList = new JList();
		 serviceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		 serviceList.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 scrollPane_3.setViewportView(serviceList);
		 
		 guestServiceVector=disService(); //Fetch guest service data from the DB and display it using this list
		 serviceList.setListData(guestServiceVector);//Initialize the list with the data from the DB
		 
		 //default select the first item 
		 serviceList.setSelectedIndex(0);
		 
		 guestSearchButton = new JButton("Guest Search");
		 guestSearchButton.setToolTipText("Please select a guest in the list");
		 //Object gItem=guestList.getSelectedValue();
		 
	 	 //no item in the guest list has been selected
		 //if(gItem==null)
	 		//guestSearchButton.setEnabled(false);
	 	 //else
	 		//guestSearchButton.setEnabled(true); 
		 
		 guestSearchButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		guestSearch();
		 	}
		 });
		 guestSearchButton.setActionCommand("guestSearchButton");
		 
		 orderButton = new JButton("Order");
		 orderButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		guestServiceOrder();
		 	}
		 });
		 
		 addServiceButton = new JButton("Add Service");
		 addServiceButton.addActionListener(new ActionListener() {
		 	public void actionPerformed(ActionEvent e) {
		 		addGuestService();
		 	}
		 });
		 GroupLayout gl_panel_4 = new GroupLayout(panel_4);
		 gl_panel_4.setHorizontalGroup(
		 	gl_panel_4.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_panel_4.createSequentialGroup()
		 			.addGap(26)
		 			.addComponent(guestSearchButton)
		 			.addPreferredGap(ComponentPlacement.RELATED, 196, Short.MAX_VALUE)
		 			.addComponent(orderButton, GroupLayout.PREFERRED_SIZE, 63, GroupLayout.PREFERRED_SIZE)
		 			.addPreferredGap(ComponentPlacement.UNRELATED)
		 			.addComponent(addServiceButton, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
		 			.addGap(24))
		 );
		 gl_panel_4.setVerticalGroup(
		 	gl_panel_4.createParallelGroup(Alignment.LEADING)
		 		.addGroup(gl_panel_4.createSequentialGroup()
		 			.addContainerGap()
		 			.addGroup(gl_panel_4.createParallelGroup(Alignment.BASELINE, false)
		 				.addComponent(guestSearchButton)
		 				.addComponent(orderButton)
		 				.addComponent(addServiceButton))
		 			.addGap(16))
		 );
		 panel_4.setLayout(gl_panel_4);
		 panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS));
		 
		 scrollPane_2 = new JScrollPane();
		 panel_2.add(scrollPane_2);
		 
		 infoTextArea = new JTextArea();
		 infoTextArea.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 infoTextArea.setEditable(false);
		 scrollPane_2.setViewportView(infoTextArea);
		 panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		 
		 scrollPane = new JScrollPane();
		 
		 guestList = new JList();
		 guestList.setFont(new Font("MS Reference Sans Serif", Font.BOLD, 14));
		 guestList.setModel(new AbstractListModel() {
		 	String[] values = new String[] {"YIFENG ZOU", "Guest1", "Guest2", "Guest3"};
		 	public int getSize() {
		 		return values.length;
		 	}
		 	public Object getElementAt(int index) {
		 		return values[index];
		 	}
		 });
		 
		 guestNameVector=disGuestName(); //Fetch guest name data from the DB and display it using this list
		 guestList.setListData(guestNameVector);//Initialize the list with the data from the DB
		 //default select the first item as default
		 guestList.setSelectedIndex(0);
		 scrollPane.setViewportView(guestList);
		 panel.add(scrollPane);
		 contentPane.setLayout(gl_contentPane);
		 
		 if(!checkPermission(Permission.OFFER_ADDITIONAL_GUEST_SERVICES)) {
			 orderButton.setEnabled(false);
			 addServiceButton.setEnabled(false);
		 }
	    } 

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equalsIgnoreCase("guestSearchButton")) {
            guestSearch();
		}
		if (e.getActionCommand().equalsIgnoreCase("roomSearchButton")) {
            
		}
		if (e.getActionCommand().equalsIgnoreCase("payMethodButton")) {
            
		}	
	}
	
	public void guestSearch(){
		String gFirstName;
        String gLastName;
        int gRoomID = 0;
        String gRoomLabel=" ";
        String guestName=" ";
        Object name=" ";
        name=guestList.getSelectedValue();
        guestName=name.toString();
        display.setText("You Select Guest: "+guestName);
        //System.out.println(name.toString());
        String gName[]=guestName.split(" ");
        gFirstName=gName[0];
        gLastName=gName[1];
        String address=" ";
        
        DAO localDAO = MasterController.getDatabaseObject();
        
        String gstSearchSQL = "Select* from GUEST where upper(FIRST_NAME)=upper('"+gFirstName+"') and upper(LAST_NAME)=upper('"+gLastName+"');";
		ResultSet rs1 = localDAO.getResult(gstSearchSQL);
        try {
			while(rs1.next()){
				gRoomID=rs1.getInt("ROOMID");
				guestID=rs1.getInt("GUEST_ID"); // Get the ID of this Guest
				address=rs1.getString("ADDRESS")+", "+rs1.getString("CITY")+", "+rs1.getString("STATE");
				//System.out.println("Guest ID is: "+guestID);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
        
        ResultSet rs2 = localDAO.getResult("Select* from ROOM where ROOMID='"+gRoomID+"';");
        try {
			while(rs2.next()){
				gRoomLabel=rs2.getObject("ROOMLABEL").toString();
				//System.out.println("Room Label is: "+gRoomLabel);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
        
        infoTextArea.setText("");
        infoTextArea.append("GUEST NAME:  "+gFirstName+" "+gLastName+"\n");
        infoTextArea.append("GUEST ROOM:  "+gRoomLabel+"\n");
        infoTextArea.append("GUEST ADDRESS:  "+address+"\n");
	}
	
	public Vector<String> disGuestName(){
		
		Vector<String> guestName = new Vector<String>();
		DAO localDAO = MasterController.getDatabaseObject();
		//ResultSet rs = localDAO.getResult("Select FIRST_NAME,LAST_NAME from GUEST");
		ResultSet rs = localDAO.getResult("Select FIRST_NAME,LAST_NAME from GUEST where GUEST_ID in (Select GUEST_ID from GUEST_RESERVATION);");
		try {
			
			while(rs.next()){
				String firstName=rs.getObject("FIRST_NAME").toString();
				String lastName=rs.getObject("LAST_NAME").toString();
				String gName=firstName+" "+lastName;
				guestName.add(gName);
				
			}
			//for(int i=0;i<guestName.size();i++)
				//System.out.println(guestName.get(i));
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return guestName;
	}
	
	public Vector<String> disService(){
		Vector<String> serviceVector=new Vector<String>();
		DAO localDAO = MasterController.getDatabaseObject();
		ResultSet rs = localDAO.getResult("Select* from GUEST_SERVICE");
		try {
			
			while(rs.next()){
				
				String serviceDes=rs.getObject("DESCRIPTION").toString();
				double servicePrice=rs.getDouble("PRICE");
				//String service=serviceDes+":    "+servicePrice;
				String service = String.format("%s:                    $%4.2f", serviceDes,servicePrice);
				serviceVector.add(service);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return serviceVector;
	}
	
	public int guestServiceOrder(){
		Object o=serviceList.getSelectedValue();
        String service="";
        service=o.toString();
        //System.out.println(service);
        String s[]=service.split(":");
        String sDescription=s[0];
        double sPrice=Double.parseDouble(s[1].replace("$", ""));
        int GSID = 0; //Guest_Service_ID
        int reservationID=-1;
        
        //System.out.println(sDescription);
        //System.out.println(sPrice);
        
        // Query to find Guest_Service_ID
        DAO localDAO = MasterController.getDatabaseObject();
		ResultSet rs = localDAO.getResult("Select* from GUEST_SERVICE where DESCRIPTION='"+sDescription+"';");
		try {
			
			while(rs.next()){
				GSID=rs.getInt("GUEST_SERVICE_ID");			
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//System.out.println("The Guest Service ID is:" + GSID);
		
		
		//Query to find Reservation_ID via GUEST_ID which get from the guestSearch()
		//String query= "select* from GUEST,GUEST_RESERVATION where GUEST_RESERVATION.GUEST_ID="+guestID+";";
		String query= "select* from GUEST,GUEST_RESERVATION where GUEST.GUEST_ID=GUEST_RESERVATION.GUEST_ID and GUEST_RESERVATION.GUEST_ID="+guestID+";";
		ResultSet rs1 = localDAO.getResult(query);
		try {
					
			while(rs1.next()){
				//reservationID=rs1.getInt("RESERVATION_ID");
				reservationID=rs1.getInt("GUEST_RESERVATION.RESERVATION_ID");
			}
					
		    } catch (SQLException e) {
			  e.printStackTrace();
		    }
		//System.out.println("RESERVATION ID is:"+reservationID);
		//System.out.println("The Guest ID is:" + guestID);
		
		//check whether the order had been placed or not
		String checkSQL="select DESCRIPTION from GUEST_SERVICE,GUEST_SERVICE_RESERVATION where "+
						"GUEST_SERVICE.GUEST_SERVICE_ID=GUEST_SERVICE_RESERVATION.GUEST_SERVICE_ID and GUEST_ID="+guestID+";";
		
		ResultSet rs2 = localDAO.getResult(checkSQL);
		try {
			
			while(rs2.next()){
				String des=rs2.getString("DESCRIPTION");
				if(sDescription.equalsIgnoreCase(des)){
					JOptionPane.showMessageDialog(contentPane,"This order has been placed!","Error",JOptionPane.ERROR_MESSAGE);
					return 0;
				}
			}
					
		    } catch (SQLException e) {
			  e.printStackTrace();
		    }
		
		String insertSQL = "INSERT INTO GUEST_SERVICE_RESERVATION(GUEST_SERVICE_ID, GUEST_ID, RESERVATION_ID)" +
        		"VALUES("+GSID+","+guestID+","+reservationID+");";
		//invalid reservation id
		if(reservationID==-1){
			JOptionPane.showMessageDialog(contentPane,"Please search a guest first!","Error",JOptionPane.ERROR_MESSAGE);
			return 0;
		}
		
        if(localDAO.updateCommand(insertSQL))
        	JOptionPane.showMessageDialog(contentPane,"Order Confirmed!");
        else
        	JOptionPane.showMessageDialog(contentPane,"Order fails!","Error",JOptionPane.ERROR_MESSAGE);
        return 1;
	}
	
	public void addGuestService(){
		String serviceDescription="";
		double price=0.0;
		userInputBox addService=new userInputBox();
		serviceDescription=addService.getDescription();
		price=addService.getPrice();
		//System.out.println("description: " + serviceDescription);
        //System.out.println("price: " + price);
        
        String insertSQL="INSERT INTO GUEST_SERVICE(DESCRIPTION,PRICE)VALUES" +
        		"('"+serviceDescription+"',"+price+");";
        DAO localDAO = MasterController.getDatabaseObject();
        // Add a user specified service into the DB
        if(!serviceDescription.equalsIgnoreCase("")&&price!=0.0){
        	if(localDAO.updateCommand(insertSQL))
            	JOptionPane.showMessageDialog(contentPane,"You Successfully Add a Guest Service!");
            else
            	JOptionPane.showMessageDialog(contentPane,"Error Occurs!","Error",JOptionPane.ERROR_MESSAGE);
        }
        //reload the serviceList where display all the available services
        Vector<String> s= disService();
        serviceList.setListData(s);
	}
	
	//class deal with user input to add a service
	class userInputBox{
		  private JTextField descriptionField;
		  private JTextField priceField;
		  private JPanel myPanel;
		  private JLabel label1;
		  private JLabel label2;
		  private String serviceDescription="";
		  private double price=0.0;

	 public userInputBox(){
	          descriptionField = new JTextField(5);
		      priceField = new JTextField(5);
		      label1 = new JLabel();
		      label2 = new JLabel();
		      myPanel = new JPanel();
		      myPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		      JLabel label = new JLabel("Description:");
		      myPanel.add(label);
		      myPanel.add(descriptionField);
		      JLabel label_1 = new JLabel("Price:");
		      myPanel.add(label_1);
		      myPanel.add(priceField);

		      int result = JOptionPane.showConfirmDialog(null, myPanel,
		               "Please Enter Service Description and Price", JOptionPane.OK_CANCEL_OPTION);
		      if (result == JOptionPane.OK_OPTION) {
		    	 serviceDescription=descriptionField.getText();
		    	 price=Double.parseDouble(priceField.getText());
		    	 //System.out.println("description: " + descriptionField.getText());
		         //System.out.println("price: " + priceField.getText());
		      }

		  }
	 
	 public String getDescription(){
		 return serviceDescription;
	 }
	 
	 public double getPrice(){
		 return price;
	 }
	}
		
}
